using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace TXLooker.Common.Core
{
    public class XmlSerializer<T> where T : class
    {
        private static XmlSerializer Serializer
        {
            get
            {
                try
                {
                    if (m_serializer == null)
                    {
                        lock (typeof(XmlSerializer<T>))
                        {
                            if (m_serializer == null)
                                m_serializer = new XmlSerializer(typeof(T));
                        }
                    }
                    return m_serializer;
                }
                catch (Exception ex)
                {
                    LogManager.WriteMessageToCustomLog("Error (Serializer) XmlSerializer " + ex.Message);
                    return m_serializer;
                }
            }
        }
        private static XmlSerializer m_serializer = null;

        public static void Serialize(T item, string filepath)
        {
            using (FileStream fstream = new FileStream(filepath, FileMode.Create))
            {
                Serializer.Serialize(fstream, item);
            }
        }
        public static T Deserialize(string filepath)
        {
            try
            {
                object item = null;

                using (FileStream fstream = new FileStream(filepath, FileMode.Open))
                {
                    item = Serializer.Deserialize(fstream);
                }

                return (T)item;
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog("Error (Desirializer) Serializer " + ex.Message);
                return null;
            }
        }

    }
}
